﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace CoreExtention.Http
{
    public interface IHttpClientFactoryHelper
    {
        Task<T> GetJsonResult<T>(string url, string postData, HttpMethod method, string authorization);
    }
    /// <summary>
    /// 通过工厂模式去管理请求对象
    /// </summary>
    public class HttpClientFactoryHelper : IHttpClientFactoryHelper
    {
        private readonly IHttpClientFactory _clientFactory;


        public HttpClientFactoryHelper(IHttpClientFactory httpClientFactory)
        {
            _clientFactory = httpClientFactory;
        }
        //public HttpClientFactoryHelper(IHttpClientFactory httpClientFactory)
        //{
        //    _clientFactory = httpClientFactory;
        //}
        /// <summary>
        /// 获取对象数据。请注意，此方法请求，对方必须直接回json对象，否则会请求失败
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="url">请求的url</param>
        /// <param name="postData">消息内容</param>
        /// <param name="method">请求方法</param>
        /// <param name="authorization">授权</param>
        /// <returns>返回的对象</returns>
        public async Task<T> GetJsonResult<T>(string url, string postData, HttpMethod method,string authorization)
        {
            T resp = default(T);
            try
            {

                var request = new HttpRequestMessage(method, url);

                //判断是否需要认证
                if (!string.IsNullOrEmpty(authorization))
                {
                    request.Headers.Add("Authorization", authorization);
                }

                var client = _clientFactory.CreateClient();

                HttpResponseMessage response;

                if (!string.IsNullOrEmpty(postData))
                {
                    HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
                    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    request.Content = httpContent;
                }
                response = await client.SendAsync(request);
                if (response != null && response.IsSuccessStatusCode)
                {
                    resp = await response.Content.ReadAsAsync<T>();
                    return resp;
                }
                else
                {
                    string error=response.ReasonPhrase;
                    return resp;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                //LogHelper.Info($"MyHttpClientHelper结束，url={client.BaseAddress},action={Utils.GetEnumDescription(action)},postData={paramStr} ,jrclientguid={jrclientguid}---------");
            }
            return resp;
        }

        protected string Sign(string message)
        {
            // NOTE： 私钥不包括私钥文件起始的-----BEGIN PRIVATE KEY-----
            //        亦不包括结尾的-----END PRIVATE KEY-----
            //string privatekey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSA6vk7r77ry3uj+8ESmz7kUdLgMtnhMzwfUcpEO4MSUhbve7O0nANhcF5NCkWBJiISO8suShN5e+7mKGW0u0tKgHVtCdYZLhzg4xKOEhKSCah7YtHryjfBGNSSrXAZ9aR2zowM6r7nHjpdqjIwqxsuROqyAElM/pu4cQpi6RbVF7GRI6t54M30o9kEFTfjULP9EcdyOgFlDUr+rvABLcaRrniXM7E3JyRLMxmM2r0fiEFExothk/DX/VtR7E8hmeTFEkzqVacQJecRf5ZcWktB0fwTU9Rz9NakHb0m+MCfkS66B5Z3v/TjXOnAaiwABVIe+tRTJEWWVHbV512tdYFAgMBAAECggEBAL4RxpOmI8EDVY2wRIDcnu+7FwxVX0GsJhKNP0cCZH9IH62wIx6ZxAHpCSYZuAmOVUIayCPw23JM5QAibjRjZ3ZVq11u86EDXxBkgSZ2864OyLAKneBdvZ7BiOZkaUPedoqBH5OaX2fiwGeDFdTEo2quwgbxhl/WQBP0TiXPlQt1l6j9b37AX89RlX0G/ItC5VaO7Z+Kp5XCstYPaehvJ7badVQNov8N4XWPQisgWpD9AJlHFa82WMhqlAh1Pl2N51WZNVNvil6rsuzAWnaInUJo8juX+faj/QC4jHCEfETUndsg7ZcyoqFc6li/arBxHFxO5ElXYjsLTkOnZYivIS0CgYEA6pbd1wEsw+AltKSN+Gt2KyVVQki4B4enIO/y/cINrEbMN5fihME+Tzo9IHcxY+aT0g9gR+VLr6XCM/H4wl38i17jGsadm6s8ITxXcn1e4L5cPD1wV9/mWf61IrjUFJeTDo1dP/jol54ZNSve0cN5LuMbBB+Tt5XNJVfygHaBPLMCgYEA5S6dhEhD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B4eGqBI/e2qRjXm4KZZSH/OsTlTvOwsFTa7youtHz5RLWF9W0nZz/VIq9HAGG7kLVHDBJuUVVEXH+7hPBIlWmepYZHEwVmdh7U/vwvcv/tbxFJNBXix6ta+pt/vCGp0lHXUyfVfYwh2t41UhTOXOlRjjXq1iZmyu";
            byte[] keyData = Convert.FromBase64String(privateKey);
            using (CngKey cngKey = CngKey.Import(keyData, CngKeyBlobFormat.Pkcs8PrivateBlob))
            using (RSACng rsa = new RSACng(cngKey))
            {
                byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
                return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
            }
        }

    }
}
